package com.xuelang.pipeline.app.pipeline.converter;

import com.xuelang.pipeline.client.pipeline.dto.PipelineInstanceDTO;
import com.xuelang.pipeline.client.pipeline.enums.PipelineInstanceEnum;
import com.xuelang.pipeline.client.pipeline.enums.TriggerWayEnum;
import com.xuelang.pipeline.domain.pipeline.PipelineInstance;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

/**
 * <p>流水线实例DTO转换器</p>
 *
 * @author : yixin.lys
 * @date : 2024-06-19 10:54
 **/
@Mapper
public interface PipelineInstanceToDTOConverter {

    PipelineInstanceToDTOConverter INSTANCE = Mappers.getMapper(PipelineInstanceToDTOConverter.class);

    /**
     * 转换为DTO
     *
     * @param target
     * @return
     */
    default PipelineInstanceDTO toDTO(PipelineInstance target) {
        if (target == null) {
            return null;
        }

        PipelineInstanceDTO.PipelineInstanceDTOBuilder pipelineInstanceDTO = PipelineInstanceDTO.builder();

        pipelineInstanceDTO.id(target.getId());
        pipelineInstanceDTO.instanceCode(target.getInstanceCode());
        pipelineInstanceDTO.applicationCode(target.getApplicationCode());
        pipelineInstanceDTO.componentCode(target.getComponentLabel());
        pipelineInstanceDTO.buildNumber(target.getBuildNumber());
        pipelineInstanceDTO.pipelineCode(target.getPipelineCode());
        pipelineInstanceDTO.pipelineName(target.getPipelineName());
        if (target.getPipelineStatus() != null) {
            pipelineInstanceDTO.pipelineStatus(PipelineInstanceEnum.fromKey(target.getPipelineStatus()).getValue());
        }
        Integer triggerType = target.getTriggerType();
        if (triggerType != null) {
            pipelineInstanceDTO.triggerType(triggerType);
            pipelineInstanceDTO.triggerTypeDisplayStr(TriggerWayEnum.fromValue(triggerType).getDesc());
        }
        pipelineInstanceDTO.contextInfo(target.getContextInfo());
        pipelineInstanceDTO.startTime(target.getStartTime());
        pipelineInstanceDTO.endTime(target.getEndTime());
        pipelineInstanceDTO.creatorId(target.getCreatorId());
        pipelineInstanceDTO.createTime(target.getCreateTime());
        pipelineInstanceDTO.updaterId(target.getUpdaterId());
        pipelineInstanceDTO.updateTime(target.getUpdateTime());
        pipelineInstanceDTO.duration(PipelineInstanceDTO.calculateDuration(target.getStartTime(),target.getEndTime()));
        pipelineInstanceDTO.remark(target.getRemark());
        return pipelineInstanceDTO.build();
    }

    ;

    /**
     * 从DTO转换
     *
     * @param target
     * @return
     */
    PipelineInstance fromDTO(PipelineInstanceDTO target);

}
